#!/bin/bash
###########################################
# 功能: 控制 main.py 启停
#
###########################################

S_DIR=$(dirname $(readlink -f $0))
cd $S_DIR

function usage() {
  echo "Usage: $0 {start|stop|restart|status}"
  exit 1
}

if [ $# -lt 1 ]; then
  usage
fi

ENV_NAME=$2
PROGRAM="/data/tools/miniconda3/bin/python main.py ${ENV_NAME}"
PID=-1

# check run user
if [[ "${USER}" != "zhangjl" ]]; then
  echo "Need be executed with zhangjl. current user: ${USER}"
  exit 1
fi

# whether to need warning message(short message or RTX)
NEED_WARNING=1
WARNING_ID=1000001

LOCAL_IP=$(/sbin/ifconfig eth1 | awk '/inet addr/{print substr($2,6)}')
if [ -z "${LOCAL_IP}" ]; then
  LOCAL_IP=$(/sbin/ifconfig eth1 | awk '/inet/{print $2}')
fi

function notify_warning() {
  local msg="[xxxx@gmail.com]: ${LOCAL_IP},$1"

  echo "WARNING: ${msg}"

  if [ ${NEED_WARNING} -ne 0 ]; then
    /usr/local/warn_agent/responseStr ${WARNING_ID} "${msg}"
  fi
}

function status() {
  PID=-1
  pid_info=$(pgrep -x -f "${PROGRAM}")
  if [[ "x${pid_info}" != "x" ]]; then
    PID=${pid_info}
    echo "'${PROGRAM}' is running. pid: ${PID}"
    return 0
  fi

  return 1
}

function start() {
  status
  if [[ ${PID} -ne -1 ]]; then
    return 0
  fi

  echo "Starting the program: ${PROGRAM}."
  nohup ${PROGRAM} 1>/dev/null 2>&1 &
  sleep 2
  status
  if [[ ${PID} -eq -1 ]]; then
    echo "Failed to start the program: ${PROGRAM}."
    return 1
  fi
  echo "Success. PID: ${PID}"
  return 0
}

function stop() {
  status
  if [[ ${PID} -eq -1 ]]; then
    echo "'${PROGRAM}' is not running."
    return 0
  fi

  echo "Stop the program: ${PROGRAM}."
  kill -15 ${PID}
  sleep 2
  status
  if [[ ${PID} -ne -1 ]]; then
    echo "Failed to stop the program: ${PROGRAM}."
    return 1
  fi
  echo "==> success"
  return 0
}

RETVAL=0
case "$1" in
status)
  status
  RETVAL=$?
  if [[ ${RETVAL} -ne 0 ]]; then
    echo "'${PROGRAM}' is not running."
  fi
  ;;
start)
  start
  RETVAL=$?
  ;;
stop)
  stop
  RETVAL=$?
  ;;
restart)
  stop
  start
  RETVAL=$?
  ;;
check)
  status
  RETVAL=$?
  if [[ ${RETVAL} -ne 0 ]]; then
    notify_warning "'${PROGRAM}' is not running. Try to restart"
    start
  fi
  ;;
*)
  usage
  ;;
esac

exit ${RETVAL}
